<!--
 * @Author: [kangjie]
 * @Date: 2022-04-20 14:58:13
 * @LastEditors: l梁先生 11238060+lhb55@user.noreply.gitee.com
 * @LastEditTime: 2022-10-21 17:15:33
 * @Description:
-->
<template>
  <div>
    <!-- 头部 -->
    <div class="header">
      <el-form :inline="true" :model="myForm" class="demo-form-inline">
        <el-form-item>
          <el-button type="primary" @click="toAdd">添加</el-button>
        </el-form-item>
        <el-form-item>
          <el-input v-model="myForm.name" placeholder="请输入名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-select v-model="myForm.status" placeholder="请选择状态" clearable>
            <el-option label="正常" value="正常" />
            <el-option label="下架" value="下架" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="myForm.productCategoryId"
            placeholder="请选择栏目"
            clearable
          >
            <el-option
              v-for="item in column"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格 -->
    <div class="container">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="index" :index="1" label="序号" />
        <el-table-column prop="id" label="产品编号" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="photo" label="图片">
          <template slot-scope="scope">
            <img :src="scope.row.photo" alt="" style="height: 20px" />
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" />
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status === '正常'" type="success"
              >正常</el-tag
            >
            <el-tag v-else type="danger">下架</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="category.name" label="所属栏目" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tag type="info" @click="toEdit(scope.row)">编辑</el-tag>
            <el-tag
              v-if="scope.row.status === '下架'"
              type="success"
              @click="onLine(scope.row.id)"
            >
              上架
            </el-tag>
            <el-tag v-else type="danger" @click="offLine(scope.row.id)"
              >下架</el-tag
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页组件 -->
    <div class="page">
      <el-pagination
        :current-page="params.page"
        :page-sizes="[2, 5, 10, 15]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 模态框 -->
    <div class="box">
      <el-dialog :title="title" :visible.sync="visible" @close="toClose">
        <el-form ref="form" :rules="rules" :model="form">
          <el-form-item
            label="产品名称"
            :label-width="formLabelWidth"
            prop="name"
          >
            <el-input
              v-model="form.name"
              autocomplete="off"
              clearable
              placeholder="请填写产品名称"
            />
          </el-form-item>
          <el-form-item
            label="所属栏目"
            :label-width="formLabelWidth"
            prop="productCategoryId"
          >
            <el-select
              v-model="form.productCategoryId"
              placeholder="请选择所属栏目"
            >
              <el-option
                v-for="item in column"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="价格" :label-width="formLabelWidth" prop="price">
            <el-input
              v-model.number="form.price"
              autocomplete="off"
              clearable
              placeholder="请输入价格"
            />
          </el-form-item>
          <el-form-item label="封面" :label-width="formLabelWidth" prop="photo"
            ><el-upload
              class="avatar-uploader"
              :action="uploadFileURL"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="form.photo" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon" /> </el-upload
          ></el-form-item>
          <el-form-item
            label="产品描述"
            :label-width="formLabelWidth"
            prop="description"
          >
            <el-input
              v-model="form.description"
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="visible = false">取 消</el-button>
          <el-button type="primary" @click="toSubmit('form')">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import {
  offline,
  online,
  pageQuery,
  pageQueryColumn,
  saveOrUpdate,
} from "@/api/product";
import { uploadFileURL } from "@/utils/config";
export default {
  data() {
    return {
      myForm: {},
      uploadFileURL,
      true: "",
      form: {},
      tableData: [],
      title: "",
      params: {
        page: 1,
        pageSize: 10,
      },
      total: 0,
      visible: false,
      formLabelWidth: "100px",
      imageUrl: "",
      textarea: "",
      column: [],
      rules: {
        name: [{ required: true, message: "请选择产品名称", trigger: "blur" }],
        productCategoryId: [
          { required: true, message: "所属栏目", trigger: "change" },
        ],
        price: [
          {
            required: true,
            message: "请输入价格",
            trigger: "blur",
            type: "number",
          },
        ],
        photo: [{ required: true, message: "请选择图片", trigger: "blur" }],
        description: [
          { required: true, message: "请填写产品描述", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getTableData();
    this.getqueryColumn();
  },
  methods: {
    // 点击编辑的方法
    toEdit(row) {
      this.title = "编辑产品信息";
      this.visible = true;
      this.form = { ...row };
      this.imageUrl = this.form.photo;
    },
    // 模态框回调
    toClose() {
      this.form = {};
      this.imageUrl = "";
      // 重置表单
      setTimeout(() => {
        this.$refs.form.resetFields();
        this.visible = false;
      }, 500);
    },
    // 下架方法
    async offLine(id) {
      const res = await offline({ id });
      this.$message({
        type: "success",
        message: res.message,
      });
      this.getTableData();
    },
    // 上架方法
    async onLine(id) {
      const res = await online({ id });
      this.$message({
        type: "success",
        message: res.message,
      });
      this.getTableData();
    },
    // 表单确定按钮   校验方法
    toSubmit(form) {
      this.$refs[form].validate(async (valid) => {
        if (valid) {
          // 添加信息
          const res = await saveOrUpdate(this.form);
          this.$message({
            type: "success",
            message: res.message,
          });
          this.visible = false;
          this.getTableData();
        } else {
          this.$message({
            type: "warning",
            message: "请输入必填项",
          });
        }
      });
    },
    // 获取栏目信息
    async getqueryColumn() {
      const res = await pageQueryColumn(this.params);
      this.column = res.data.list;
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.photo = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 查询
    onSearch() {
      this.getTableData();
      this.params.page = 1;
    },
    // 添加
    toAdd() {
      this.title = "添加产品信息";
      this.visible = true;
    },
    // 获取表格数据
    async getTableData() {
      const temp = { ...this.myForm, ...this.params };
      for (const key in temp) {
        if (!temp[key]) {
          delete temp[key];
        }
      }
      const res = await pageQuery(temp);
      this.tableData = res.data.list;
      this.total = res.data.total;
    },
    // 每页几条数据
    handleSizeChange(pageSize) {
      this.params.pageSize = pageSize;
      this.params.page = 1;
      this.getTableData();
    },
    // 第几页
    handleCurrentChange(page) {
      this.params.page = page;
      this.getTableData();
    },
  },
};
</script>
<style>
.page {
  text-align: right;
  margin-top: 10px;
  margin-right: 100px;
}
</style>
